import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { UpdateFolderDto } from './dto/update-folder.dto';
import { CreateFolderDto } from './dto/create-folder.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Folder } from './entities/folder.entity';
import { Repository } from 'typeorm';
import { WINSTON_LOGGER_TOKEN } from 'src/winston/winston.module';
import { CreateGroupToFolderlistDto } from './dto/create-grouptofolder.dto';
import { GroupToFolderlist } from './entities/grouptofolder.entity';
import { User } from 'src/user/entities/user.entity';
import { usertogroup } from 'src/group/entities/usertogroup.entity';

@Injectable()
export class FolderService {
  constructor(
    @InjectRepository(Folder)
    private readonly folderRepository: Repository<Folder>,
    @InjectRepository(GroupToFolderlist)
    private readonly groupToFolderRepository: Repository<GroupToFolderlist>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(usertogroup)
    private readonly usertogroupRepository: Repository<usertogroup>,
  ) {}

  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;

  async deleteFolder(id: string) {
    const result = await this.folderRepository.delete({ id: id });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }
  async updateFolder(id: string, updateFolderDto: UpdateFolderDto) {
    const oldFolder = await this.folderRepository.findOne({
      where: { id: id },
    });
    if (!oldFolder) {
      return '未找到匹配的记录，没有进行更新操作';
    }
    try {
      const updateFolder = this.folderRepository.merge(
        oldFolder,
        updateFolderDto,
      );
      await this.folderRepository.save(updateFolder);
      return '修改文件夹属性成功!';
    } catch (err) {
      this.logger.error(
        `更新文件夹属性失败${err}`,
        `${FolderService.name}-${this.updateFolder.name}`,
      );
      throw new BadRequestException('更新文件夹属性失败');
    }
  }
  async createFolder(createFolderDto: CreateFolderDto) {
    const insertItem = this.folderRepository.create(createFolderDto);
    const res = await this.folderRepository.insert(insertItem);
    return res.raw[0].id;
  }

  getFolderById(id: string) {
    return this.folderRepository.findOne({ where: { id: id } });
  }

  async getChildFolderuuidByFolderuuid(folderuuid: string) {
    const allFolderUuids: string[] = [folderuuid]; // 初始化包含最初传入 id 的数组
    let currentFolderUuid = folderuuid;

    while (true) {
      const childFolder = await this.folderRepository.findOne({
        where: { folder_id: currentFolderUuid },
        select: ['id'], // 只查询 id 属性
      });

      if (!childFolder) {
        break; // 如果没有子文件夹，退出循环
      }

      allFolderUuids.push(childFolder.id); // 将子文件夹的 id 添加到数组中
      currentFolderUuid = childFolder.id; // 更新当前查询的文件夹 id
    }

    return allFolderUuids; // 返回所有查询到的 id
  }

  getRootFolderByUser(email: any) {
    return this.folderRepository.find({
      where: { folder_id: '-1', creator: email },
    });
  }

  getFolderUserByFolderuuid(folderuuid: string, email: any) {
    return this.folderRepository.find({
      where: { folder_id: folderuuid, creator: email, role: 'person' },
    });
  }

  moveFolderToGroup(createGroupToFolderlistDto: CreateGroupToFolderlistDto) {
    throw new Error('Method not implemented.');
  }
  async getFolderItemByGroupuuidFolderuuid(
    groupuuid: string,
    folderuuid: string,
  ) {
    const folderList = await this.groupToFolderRepository.find({
      where: {
        groupuuid: groupuuid,
      },
    });
    const folderPromises = folderList.map(async (folderItem) => {
      const folderInfo = await this.folderRepository.findOne({
        where: {
          id: folderItem.folderuuid,
          folder_id: folderuuid,
          role: 'group',
        },
      });
      if (folderInfo) {
        const userItem = await this.userRepository.findOne({
          where: {
            email: folderItem.belong,
          },
        });
        const usertogroupItem = await this.usertogroupRepository.findOne({
          where: {
            useruuid: userItem?.id,
            groupuuid: groupuuid,
          },
        });
        (folderInfo as any).uploader_nickname = usertogroupItem?.groupnickname;
        (folderInfo as any).folderToGroupId = folderItem.id;
        return folderInfo;
      } else {
        return null;
      }
    });
    const folderOfGroupList = await Promise.all(folderPromises);
    return folderOfGroupList.filter((folder) => folder !== null) as Folder[];
  }
  async deleteFolderItemFromGroup(folder_uuid: string) {
    try {
      const result = await this.groupToFolderRepository.delete({
        folderuuid: folder_uuid,
      });
      await this.deleteFolder(folder_uuid);
      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      throw '删除小组文件夹记录失败';
    }
  }

  moveFolderItemToUser(createFolderDto: CreateFolderDto, email: any) {
    throw new Error('Method not implemented.');
  }
  async createFolderToGroup(
    createFolderDto: CreateFolderDto,
    groupuuid: string,
  ) {
    try {
      const folderuuid = await this.createFolder(createFolderDto);
      const createGroupToFolderlistDto = new CreateGroupToFolderlistDto();
      createGroupToFolderlistDto.belong = createFolderDto.creator;
      createGroupToFolderlistDto.folderuuid = folderuuid;
      createGroupToFolderlistDto.groupuuid = groupuuid;
      const insertItem = this.groupToFolderRepository.create(
        createGroupToFolderlistDto,
      );
      await this.groupToFolderRepository.insert(insertItem);
      return '新建小组文件夹成功';
    } catch (error) {
      this.logger.error(
        `更新地图矢量条目失败${error}`,
        `${FolderService.name}-${this.createFolderToGroup.name}`,
      );
      throw new BadRequestException('新建小组文件夹失败');
    }
  }

  async getChildFolderByFolderuuid(folderuuid: string) {
    const res = await this.folderRepository.find({
      select: ['id'], // 只查询 id 字段
      where: { folder_id: folderuuid },
    });
    return res.map((item) => ({ ...item, type: 'folder' }));
  }
}
